<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 御宅男 <530765310@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 地区模型
// +----------------------------------------------------------------------
namespace app\api\model;

use think\Model;

class SpecialOrder extends ApiModel
{
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';

    protected $status = [0 => '未支付', 1 => '已支付', 2 => "取消订单"];


    public function getSpecOrder($params = array())
    {
        $status = $params['status'] ?? '';
        if ($params['status'] != '') {
            $map['status'] = $status;
        }
        $map['member_id'] = $params['uid'];
        $order = self::where($map)
            ->field('id,out_trade_no,special_cate_name,title,status,amount,pay_amount,create_time,pay_time,unit,pay_type')
            ->order('create_time desc')
            ->paginate(10);
        foreach ($order as &$value) {
            $value['status_name'] = $this->status[$value['status']] ?? '';
            $value['pay_time'] = $value['pay_time'] ? date('Y-m-d H:i:s', $value['pay_time']) : '';

        }

        return $this->api_success('获取成功', $order);
    }


    public function getSpecOrderDetail($params = array())
    {
        $order_id = $params['order_id'] ?? '';
        $order = self::where(['out_trade_no' => $order_id])
            ->field('id,out_trade_no,special_cate_name,title,status,amount,pay_amount,create_time,pay_time,unit,pay_type')
            ->find();
        if (!$order) {
            return $this->api_error('订单不存在');
        }
        $order['status_name'] = $this->status[$order['status']] ?? '';
        $order['pay_time'] = $order['pay_time'] ? date('Y-m-d H:i:s', $order['pay_time']) : '';

        return $this->api_success('获取成功', $order);
    }


    public function cancelSpecOrder($params)
    {
        $order_id = $params['order_id'] ?? '';
        $order = self::where(['out_trade_no' => $order_id, 'status' => 0])->find();
        if (!$order) {
            return $this->api_error('订单不存在');
        }
        if (!self::where(['out_trade_no' => $order_id])->update(['status' => 2])) {
            return $this->api_error('操作失败，请刷新后重试');
        }
        return $this->api_success('取消成功');

    }
}
